<template>
  <div class="blog-sidebar">
    <div class="sidebar-content">
      <!-- 最近编辑 -->
      <div class="sidebar-section">
        <div class="section-header" @click="toggleSection('recentDrafts')">
          <i class="fas fa-clock" />
          <span>最近编辑</span>
          <i
            class="fas fa-chevron-down section-arrow"
            :class="{ rotated: expandedSections.recentDrafts }"
          />
        </div>
        <transition name="collapse">
          <div v-show="expandedSections.recentDrafts" class="section-content">
            <div v-if="recentDraftsLoading" class="loading-spinner">
              <i class="fas fa-spinner fa-spin" />
            </div>
            <div v-else-if="recentDrafts.length === 0" class="empty-state">
              <i class="fas fa-file-alt" />
              <span>暂无草稿</span>
            </div>
            <div v-else class="draft-list">
              <div
                v-for="draft in recentDrafts"
                :key="draft.blogId"
                class="draft-item"
                :class="{ active: isActiveDraft(draft.blogId) }"
                @click="openDraft(draft)"
              >
                <div class="draft-info">
                  <h4 class="draft-title">
                    {{ draft.blogTitle || '未命名草稿' }}
                  </h4>
                  <p class="draft-meta">
                    {{ formatTime(draft.updateTime) }} · {{ draft.wordCount || 0 }}字
                  </p>
                </div>
                <div class="draft-actions">
                  <button class="action-btn" @click.stop="deleteDraft(draft.blogId)">
                    <i class="fas fa-trash" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </transition>
      </div>

      <!-- 全部文章 -->
      <div class="sidebar-section">
        <div class="section-header" @click="toggleSection('allArticles')">
          <i class="fas fa-folder" />
          <span>全部文章</span>
          <i
            class="fas fa-chevron-down section-arrow"
            :class="{ rotated: expandedSections.allArticles }"
          />
        </div>
        <transition name="collapse">
          <div v-show="expandedSections.allArticles" class="section-content">
            <!-- 未归纳 -->
            <div class="subsection">
              <div class="subsection-header" @click="toggleSubsection('uncategorized')">
                <i class="fas fa-file" />
                <span>未归纳</span>
                <button class="add-article-btn" title="新建文章" @click.stop="createNewArticle">
                  <i class="fas fa-plus" />
                </button>
                <span class="count-badge">{{ uncategorizedCount }}</span>
                <i
                  class="fas fa-chevron-down subsection-arrow"
                  :class="{ rotated: expandedSubsections.uncategorized }"
                />
              </div>
              <transition name="collapse">
                <div v-show="expandedSubsections.uncategorized" class="subsection-content">
                  <div v-if="uncategorizedLoading" class="loading-spinner">
                    <i class="fas fa-spinner fa-spin" />
                  </div>
                  <div v-else-if="uncategorizedArticles.length === 0" class="empty-state">
                    <span>暂无未归纳文章</span>
                  </div>
                  <div v-else class="article-list">
                    <div
                      v-for="article in uncategorizedArticles"
                      :key="article.blogId"
                      class="article-item"
                      :class="{ active: isActiveArticle(article.blogId) }"
                      @click="openArticle(article)"
                    >
                      <div class="article-info">
                        <h4 class="article-title">
                          {{ article.blogTitle }}
                        </h4>
                        <p class="article-meta">
                          {{ formatTime(article.updateTime) }}
                        </p>
                      </div>
                      <div class="article-actions">
                        <button class="action-btn" @click.stop="deleteArticle(article)">
                          <i class="fas fa-trash" />
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </transition>
            </div>

            <!-- 已归纳 -->
            <div class="subsection">
              <div class="subsection-header" @click="toggleSubsection('categorized')">
                <i class="fas fa-folder-open" />
                <span>已归纳</span>
                <button class="add-collection-btn" title="新建合集" @click.stop="addNewCollection">
                  <i class="fas fa-plus" />
                </button>
                <i
                  class="fas fa-chevron-down subsection-arrow"
                  :class="{ rotated: expandedSubsections.categorized }"
                />
              </div>
              <transition name="collapse">
                <div v-show="expandedSubsections.categorized" class="subsection-content">
                  <div v-if="collectionsLoading" class="loading-spinner">
                    <i class="fas fa-spinner fa-spin" />
                  </div>
                  <div v-else class="collection-list">
                    <!-- 新建合集内联编辑 -->
                    <div v-if="isCreatingNew" class="collection-item editing-item">
                      <div class="collection-header">
                        <i class="fas fa-folder" />
                        <input
                          ref="newCollectionInput"
                          v-model="newCollectionName"
                          class="collection-name-input"
                          placeholder="输入合集名称..."
                          @keyup.enter="confirmCreateCollection"
                          @keyup.esc="cancelCreateCollection"
                          @blur="cancelCreateCollection"
                        />
                        <div class="editing-actions">
                          <button class="confirm-btn" title="确认" @click="confirmCreateCollection">
                            <i class="fas fa-check" />
                          </button>
                          <button class="cancel-btn" title="取消" @click="cancelCreateCollection">
                            <i class="fas fa-times" />
                          </button>
                        </div>
                      </div>
                    </div>

                    <!-- 空状态 -->
                    <div v-if="!isCreatingNew && collections.length === 0" class="empty-state">
                      <i class="fas fa-folder-open" />
                      <span>暂无合集</span>
                      <button class="create-first-collection-btn" @click="addNewCollection">
                        <i class="fas fa-plus" />
                        创建第一个合集
                      </button>
                    </div>

                    <!-- 合集列表 -->
                    <template v-for="collection in collections" :key="collection.id">
                      <div v-if="editingCollectionId !== collection.id" class="collection-item">
                        <div class="collection-header" @click="toggleCollection(collection.id)">
                          <i class="fas fa-folder" />
                          <span class="collection-name">{{ collection.name }}</span>
                          <span class="collection-count">{{ collection.blogCount || 0 }}</span>
                          <div class="collection-actions">
                            <button
                              class="action-btn add-article-btn"
                              title="在合集中新建文章"
                              @click.stop="createNewArticleInCollection(collection)"
                            >
                              <i class="fas fa-file" />
                            </button>
                            <button
                              class="action-btn edit-btn"
                              title="编辑合集名称"
                              @click.stop="startEditCollection(collection)"
                            >
                              <i class="fas fa-edit" />
                            </button>
                            <button
                              class="action-btn delete-btn"
                              title="删除合集"
                              @click.stop="deleteCollection(collection)"
                            >
                              <i class="fas fa-trash" />
                            </button>
                          </div>
                          <i
                            class="fas fa-chevron-down collection-arrow"
                            :class="{
                              rotated: expandedCollections[collection.id]
                            }"
                          />
                        </div>
                        <transition name="collapse">
                          <div
                            v-show="expandedCollections[collection.id]"
                            class="collection-content"
                          >
                            <div
                              v-if="loadingCollectionBlogs[collection.id]"
                              class="loading-spinner"
                            >
                              <i class="fas fa-spinner fa-spin" />
                            </div>
                            <div
                              v-else-if="collectionBlogs[collection.id]?.length === 0"
                              class="empty-state"
                            >
                              <span>该合集中暂无文章</span>
                            </div>
                            <div v-else class="article-list">
                              <div
                                v-for="blog in collectionBlogs[collection.id]"
                                :key="blog.blogId"
                                class="article-item"
                                :class="{
                                  active: isActiveArticle(blog.blogId)
                                }"
                                @click="openArticle(blog)"
                              >
                                <div class="article-info">
                                  <h4 class="article-title">
                                    {{ blog.blogTitle }}
                                  </h4>
                                  <p class="article-meta">
                                    {{ formatTime(blog.updateTime) }}
                                  </p>
                                </div>
                                <div class="article-actions">
                                  <button class="action-btn" @click.stop="deleteArticle(blog)">
                                    <i class="fas fa-trash" />
                                  </button>
                                </div>
                              </div>
                            </div>
                          </div>
                        </transition>
                      </div>

                      <!-- 编辑状态 -->
                      <div v-else class="collection-item editing-item">
                        <div class="collection-header">
                          <i class="fas fa-folder" />
                          <input
                            ref="editingCollectionInput"
                            v-model="editingCollectionName"
                            class="collection-name-input"
                            placeholder="输入合集名称..."
                            @keyup.enter="confirmEditCollection"
                            @keyup.esc="cancelEditCollection"
                            @blur="cancelEditCollection"
                          />
                          <div class="editing-actions">
                            <button class="confirm-btn" title="确认" @click="confirmEditCollection">
                              <i class="fas fa-check" />
                            </button>
                            <button class="cancel-btn" title="取消" @click="cancelEditCollection">
                              <i class="fas fa-times" />
                            </button>
                          </div>
                        </div>
                      </div>
                    </template>
                  </div>
                </div>
              </transition>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { deleteBlog, getRecentDrafts } from '@/api/blog';
import { BlogInfo } from '@/api/blog/types';
import {
  deleteCollection,
  getBlogsByCollectionId,
  getCollectionsByUser,
  getUncategorizedBlogs,
  saveCollection,
  updateCollection
} from '@/api/collection';
import { useBlogStore } from '@/store/modules/blog';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 定义事件和属性
const emit = defineEmits(['select-article', 'create-new-article', 'article-deleted']);
const props = defineProps({
  editorState: {
    type: Object,
    required: true
  }
});

const router = useRouter();
const route = useRoute();
const blogStore = useBlogStore();

// 组件状态
const expandedSections = reactive({
  recentDrafts: true,
  allArticles: false
});
const expandedSubsections = reactive({
  uncategorized: false,
  categorized: false
});
const expandedCollections = reactive({});

// 数据状态
const recentDrafts = ref<BlogInfo[]>([]);
const recentDraftsLoading = ref(false);
const uncategorizedArticles = ref<BlogInfo[]>([]);
const uncategorizedLoading = ref(false);
const collections = ref([]);
const collectionsLoading = ref(false);
const collectionBlogs = reactive({});
const loadingCollectionBlogs = reactive({});

// 合集管理状态
const isCreatingNew = ref(false);
const newCollectionName = ref('');
const editingCollectionId = ref(null);
const editingCollectionName = ref('');
const newCollectionInput = ref();
const editingCollectionInput = ref();
const blurTimeoutId = ref(null);

// 计算属性
const uncategorizedCount = ref(0);

// 当前选中的文章ID - 由父组件传入
const selectedArticleId = ref<string>();

// 设置当前选中的文章ID
const setSelectedArticleId = (blogId: string) => {
  selectedArticleId.value = blogId;
};

const toggleSection = async (section: string) => {
  const isCurrentlyExpanded = expandedSections[section];

  if (isCurrentlyExpanded) {
    // 如果当前分类已经展开，则折叠所有分类（允许完全折叠）
    Object.keys(expandedSections).forEach(key => {
      expandedSections[key] = false;
    });
  } else {
    // 手风琴效果：只展开一个主分类
    Object.keys(expandedSections).forEach(key => {
      expandedSections[key] = key === section;
    });

    // 展开时智能刷新相关数据
    if (section === 'recentDrafts') {
      // 每次展开最近编辑都刷新，获取最新数据
      await loadRecentDrafts();
    } else if (section === 'allArticles') {
      // 展开全部文章时，刷新未归纳文章和合集列表
      const loadPromises = [];

      // 总是刷新未归纳文章和合集，确保数据最新
      loadPromises.push(loadUncategorizedArticles());
      loadPromises.push(loadCollections());

      if (loadPromises.length > 0) {
        await Promise.all(loadPromises);
      }
    }
  }
};

const toggleSubsection = (subsection: string) => {
  const isExpanding = !expandedSubsections[subsection];
  expandedSubsections[subsection] = isExpanding;

  // 数据加载逻辑已在 toggleSection 中处理，这里只需要切换展开状态
};

const toggleCollection = async (collectionId: number) => {
  expandedCollections[collectionId] = !expandedCollections[collectionId];

  // 如果展开且还没有加载文章，则加载文章
  if (expandedCollections[collectionId] && !collectionBlogs[collectionId]) {
    await loadCollectionBlogs(collectionId);
  }
};

const loadRecentDrafts = async () => {
  try {
    recentDraftsLoading.value = true;
    const response = await getRecentDrafts(10);
    recentDrafts.value =
      response.data?.map(blog => ({
        ...blog,
        wordCount: blog.blogContent?.length || 0
      })) || [];
  } catch (error) {
    console.error('加载最近草稿失败:', error);
    ElMessage.error('加载最近草稿失败');
  } finally {
    recentDraftsLoading.value = false;
  }
};

const loadCollections = async () => {
  // 避免重复加载
  if (collectionsLoading.value) return;

  try {
    collectionsLoading.value = true;
    console.log('开始加载合集列表...'); // 调试日志
    const response = await getCollectionsByUser();
    console.log('获取合集响应:', response); // 调试日志
    collections.value = response.data || [];
    console.log('当前合集列表:', collections.value); // 调试日志
  } catch (error) {
    console.error('加载用户合集失败:', error);
    ElMessage.error('加载用户合集失败');
  } finally {
    collectionsLoading.value = false;
  }
};

const loadCollectionBlogs = async (collectionId: number) => {
  try {
    loadingCollectionBlogs[collectionId] = true;
    const response = await getBlogsByCollectionId({
      id: collectionId,
      pageNum: 1,
      pageSize: 20
    });
    collectionBlogs[collectionId] = response.data?.list || [];
  } catch (error) {
    console.error(`加载合集${collectionId}的文章失败:`, error);
    ElMessage.error('加载合集中的文章失败');
  } finally {
    loadingCollectionBlogs[collectionId] = false;
  }
};

const loadUncategorizedArticles = async () => {
  // 避免重复加载
  if (uncategorizedLoading.value) return;

  try {
    uncategorizedLoading.value = true;
    const response = await getUncategorizedBlogs({
      id: 0, // 未归纳文章不需要ID
      pageNum: 1,
      pageSize: 20
    });
    uncategorizedArticles.value = response.data?.list || [];
    uncategorizedCount.value = response.data?.total || 0;
    console.log('加载未归纳文章:', uncategorizedArticles.value);
  } catch (error) {
    console.error('加载未归纳文章失败:', error);
    ElMessage.error('加载未归纳文章失败');
  } finally {
    uncategorizedLoading.value = false;
  }
};

const openDraft = (draft: any) => {
  emit('select-article', draft);
};

const openArticle = (article: any) => {
  emit('select-article', article);
};

const deleteDraft = async (blogId: string) => {
  try {
    await ElMessageBox.confirm('确定要删除这个草稿吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 调用删除API
    await deleteBlog([blogId]);

    // 从列表中移除
    recentDrafts.value = recentDrafts.value.filter(draft => draft.blogId !== blogId);

    ElMessage.success('草稿已删除');

    // 通知父组件文章被删除
    emit('article-deleted', blogId);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除草稿失败:', error);
      ElMessage.error('删除草稿失败');
    }
  }
};

// 通用文章删除功能
const deleteArticle = async (article: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文章"${article.blogTitle || '未命名文章'}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 调用删除API
    await deleteBlog([article.blogId]);

    // 从各个列表中移除文章
    // 1. 从未归纳文章中移除
    uncategorizedArticles.value = uncategorizedArticles.value.filter(
      item => item.blogId !== article.blogId
    );

    // 2. 从合集文章中移除
    Object.keys(collectionBlogs).forEach(collectionId => {
      if (collectionBlogs[collectionId]) {
        collectionBlogs[collectionId] = collectionBlogs[collectionId].filter(
          (item: any) => item.blogId !== article.blogId
        );
      }
    });

    // 3. 从最近编辑中移除（如果在其中）
    recentDrafts.value = recentDrafts.value.filter(item => item.blogId !== article.blogId);

    ElMessage.success('文章已删除');

    // 通知父组件文章被删除
    emit('article-deleted', article.blogId);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error);
      ElMessage.error('删除文章失败');
    }
  }
};

const isActiveDraft = (blogId: string) => selectedArticleId.value === blogId;

const isActiveArticle = (blogId: string) => selectedArticleId.value === blogId;

const formatTime = (time: string | Date) => {
  if (!time) return '';

  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60));
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60));
      return minutes <= 1 ? '刚刚' : `${minutes}分钟前`;
    }
    return `${hours}小时前`;
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString('zh-CN');
  }
};

// 合集管理方法
const addNewCollection = () => {
  isCreatingNew.value = true;
  newCollectionName.value = '';
  // 确保已归纳部分是展开的
  expandedSubsections.categorized = true;
  // 下一帧聚焦输入框
  setTimeout(() => {
    newCollectionInput.value?.focus();
  }, 100);
};

const confirmCreateCollection = async () => {
  // 清除延迟执行的取消操作
  if (blurTimeoutId.value) {
    clearTimeout(blurTimeoutId.value);
    blurTimeoutId.value = null;
  }

  const name = newCollectionName.value.trim();
  if (!name) {
    ElMessage.warning('请输入合集名称');
    return;
  }

  try {
    console.log('开始创建合集:', name); // 调试日志
    const response = await saveCollection({ name });
    console.log('创建合集响应:', response); // 调试日志

    // 先立即将新合集添加到列表中（临时方案）
    if (response.data?.id) {
      const newCollection = {
        id: response.data.id,
        name,
        description: '',
        blogCount: 0,
        createTime: new Date().toISOString()
      };
      collections.value.unshift(newCollection);
      console.log('手动添加新合集到列表:', newCollection);
    } else {
      // 如果API没有返回完整数据，仍然尝试重新加载
      console.log('API响应不完整，尝试重新加载列表');
      await loadCollections();
    }

    ElMessage.success('合集创建成功');
    isCreatingNew.value = false;
    newCollectionName.value = '';
  } catch (error) {
    console.error('创建合集失败:', error);
    ElMessage.error('创建合集失败');
  }
};

const cancelCreateCollection = () => {
  // 清除之前的延迟执行
  if (blurTimeoutId.value) {
    clearTimeout(blurTimeoutId.value);
  }

  // 延迟执行，给按钮点击事件留出时间
  blurTimeoutId.value = setTimeout(() => {
    isCreatingNew.value = false;
    newCollectionName.value = '';
  }, 150);
};

const startEditCollection = (collection: any) => {
  editingCollectionId.value = collection.id;
  editingCollectionName.value = collection.name;
  // 下一帧聚焦输入框
  setTimeout(() => {
    editingCollectionInput.value?.focus();
    editingCollectionInput.value?.select();
  }, 100);
};

const confirmEditCollection = async () => {
  // 清除延迟执行的取消操作
  if (blurTimeoutId.value) {
    clearTimeout(blurTimeoutId.value);
    blurTimeoutId.value = null;
  }

  const name = editingCollectionName.value.trim();
  if (!name) {
    ElMessage.warning('请输入合集名称');
    return;
  }

  try {
    console.log('开始更新合集:', editingCollectionId.value, name); // 调试日志
    const response = await updateCollection({
      id: editingCollectionId.value,
      name
    });
    console.log('更新合集响应:', response);

    // 立即更新本地列表中的合集名称
    const collectionIndex = collections.value.findIndex(c => c.id === editingCollectionId.value);
    if (collectionIndex !== -1) {
      collections.value[collectionIndex].name = name;
      console.log('手动更新合集名称:', name);
    }

    ElMessage.success('合集更新成功');
    editingCollectionId.value = null;
    editingCollectionName.value = '';

    // 可选：仍然重新加载以确保数据同步
    // await loadCollections();
  } catch (error) {
    console.error('更新合集失败:', error);
    ElMessage.error('更新合集失败');
  }
};

const cancelEditCollection = () => {
  // 清除之前的延迟执行
  if (blurTimeoutId.value) {
    clearTimeout(blurTimeoutId.value);
  }

  // 延迟执行，给按钮点击事件留出时间
  blurTimeoutId.value = setTimeout(() => {
    editingCollectionId.value = null;
    editingCollectionName.value = '';
  }, 150);
};

const deleteCollection = async (collection: any) => {
  try {
    // 检查合集是否有文章
    if (collection.blogCount > 0) {
      ElMessage.warning('该合集中还有文章，无法删除');
      return;
    }

    await ElMessageBox.confirm(`确定要删除合集"${collection.name}"吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await deleteCollection([collection.id]);
    if (response.data) {
      ElMessage.success('合集删除成功');
      await loadCollections(); // 重新加载合集列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除合集失败:', error);
      ElMessage.error('删除合集失败');
    }
  }
};

// 新建文章方法
const createNewArticle = async () => {
  try {
    // 检查是否有未保存的更改
    if (props.editorState.hasUnsavedChanges) {
      await ElMessageBox.confirm('您有未保存的更改，确定要创建新文章吗？', '提示', {
        confirmButtonText: '确定创建',
        cancelButtonText: '取消',
        type: 'warning'
      });
    }

    // 创建新文章本地模板
    await blogStore.initializeNewArticle();

    ElMessage.success('新文章已创建，开始编辑吧');

    // 通知父组件创建新文章
    emit('create-new-article');

    // 新创建的文章没有ID，所以不需要更新侧边栏选中状态
    // 第一次保存后才会有ID，届时侧边栏会自动刷新
  } catch (error) {
    if (error !== 'cancel') {
      console.error('创建新文章失败:', error);
      ElMessage.error('创建新文章失败');
    }
  }
};

// 在合集中创建文章
const createNewArticleInCollection = async (collection: any) => {
  try {
    // 检查是否有未保存的更改
    if (props.editorState.hasUnsavedChanges) {
      await ElMessageBox.confirm('您有未保存的更改，确定要创建新文章吗？', '提示', {
        confirmButtonText: '确定创建',
        cancelButtonText: '取消',
        type: 'warning'
      });
    }

    // 创建新文章本地模板
    await blogStore.initializeNewArticle();

    // 设置合集ID（文章保存时会自动关联到该合集）
    await blogStore.setBlogInfo(
      {
        collectionId: collection.id
      },
      true
    );

    ElMessage.success(`已在合集"${collection.name}"中创建新文章，开始编辑吧`);

    // 通知父组件创建新文章
    emit('create-new-article');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('在合集中创建文章失败:', error);
      ElMessage.error('在合集中创建文章失败');
    }
  }
};

// 暴露方法给父组件
defineExpose({
  setSelectedArticleId,
  loadRecentDrafts,
  loadCollections,
  loadUncategorizedArticles
});

// 生命周期
onMounted(async () => {
  // 只加载最近编辑的内容，其他内容延迟加载
  await loadRecentDrafts();
});
</script>

<style scoped lang="scss">
.blog-sidebar {
  width: 320px;
  height: 100vh;
  background: #ffffff;
  border-right: 1px solid #e1e5e9;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.06);

  .sidebar-header {
    height: 64px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    border-bottom: 1px solid #e1e5e9;
    background: #f8f9fa;

    .collapse-btn {
      width: 32px;
      height: 32px;
      border: none;
      background: transparent;
      border-radius: 6px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;

      &:hover {
        background: #e1e5e9;
      }

      i {
        color: #5f6368;
        font-size: 16px;
      }
    }

    .sidebar-title {
      margin-left: 12px;
      font-weight: 600;
      color: #202124;
      font-size: 16px;
    }
  }

  .sidebar-content {
    flex: 1;
    overflow-y: auto;
    padding: 16px 0;

    .sidebar-section {
      margin-bottom: 8px;

      .section-header {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        cursor: pointer;
        transition: background-color 0.2s ease;
        user-select: none;

        &:hover {
          background: #f1f3f4;
        }

        i {
          color: #5f6368;
          font-size: 14px;
          margin-right: 12px;
        }

        span {
          flex: 1;
          font-weight: 500;
          color: #202124;
          font-size: 14px;
        }

        .section-arrow {
          font-size: 12px;
          color: #5f6368;
          transition: transform 0.2s ease;

          &.rotated {
            transform: rotate(-90deg);
          }
        }
      }

      .section-content {
        background: #fafbfc;
        border-left: 3px solid #1967d2;
        margin-left: 16px;
      }
    }

    .subsection {
      border-bottom: 1px solid #e1e5e9;

      &:last-child {
        border-bottom: none;
      }

      .subsection-header {
        display: flex;
        align-items: center;
        padding: 10px 16px;
        cursor: pointer;
        transition: background-color 0.2s ease;
        user-select: none;

        &:hover {
          background: #f1f3f4;
        }

        i {
          color: #5f6368;
          font-size: 12px;
          margin-right: 10px;
        }

        span {
          flex: 1;
          font-size: 13px;
          color: #5f6368;
        }

        .count-badge {
          background: #e8f0fe;
          color: #1967d2;
          padding: 2px 6px;
          border-radius: 10px;
          font-size: 11px;
          font-weight: 500;
          margin-right: 8px;
        }

        .subsection-arrow {
          font-size: 10px;
          color: #5f6368;
          transition: transform 0.2s ease;

          &.rotated {
            transform: rotate(-90deg);
          }
        }

        .add-collection-btn,
        .add-article-btn {
          width: 20px;
          height: 20px;
          border: none;
          background: #e8f0fe;
          border-radius: 50%;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.2s ease;
          margin-right: 8px;

          &:hover {
            background: #d2e3fc;
            transform: scale(1.1);
          }

          i {
            color: #1967d2;
            font-size: 10px;
          }
        }
      }

      .subsection-content {
        background: #ffffff;
      }
    }

    .collection-item {
      border-bottom: 1px solid #f1f3f4;

      .collection-header {
        display: flex;
        align-items: center;
        padding: 8px 16px 8px 24px;
        cursor: pointer;
        transition: background-color 0.2s ease;
        user-select: none;

        &:hover {
          background: #f8f9fa;
        }

        i {
          color: #fbbc04;
          font-size: 12px;
          margin-right: 8px;
        }

        .collection-name {
          flex: 1;
          font-size: 13px;
          color: #5f6368;
        }

        .collection-count {
          background: #fef7e0;
          color: #f9ab00;
          padding: 1px 5px;
          border-radius: 8px;
          font-size: 10px;
          font-weight: 500;
          margin-right: 8px;
        }

        .collection-arrow {
          font-size: 10px;
          color: #5f6368;
          transition: transform 0.2s ease;

          &.rotated {
            transform: rotate(-90deg);
          }
        }

        .collection-actions {
          display: flex;
          gap: 4px;
          margin-right: 8px;
          opacity: 0;
          transition: opacity 0.2s ease;

          .action-btn {
            width: 20px;
            height: 20px;
            border: none;
            background: transparent;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;

            &:hover {
              background: #f1f3f4;
            }

            i {
              font-size: 10px;
            }

            &.add-article-btn i {
              color: #1967d2;
            }

            &.edit-btn i {
              color: #5f6368;
            }

            &.delete-btn i {
              color: #ea4335;
            }
          }
        }

        &:hover .collection-actions {
          opacity: 1;
        }
      }

      // 编辑状态样式
      &.editing-item {
        background: #f8f9fa;
        border: 1px solid #e8eaed;
        border-radius: 8px;
        margin: 4px 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        animation: slideIn 0.2s ease;

        .collection-header {
          padding: 10px 16px 10px 16px;
          cursor: default;

          &:hover {
            background: transparent;
          }

          .collection-name-input {
            flex: 1;
            font-size: 13px;
            color: #202124;
            background: #ffffff;
            border: 1px solid #dadce0;
            border-radius: 4px;
            padding: 6px 8px;
            outline: none;
            transition: all 0.2s ease;
            margin-right: 8px;

            &:focus {
              border-color: #1967d2;
              box-shadow: 0 0 0 2px rgba(25, 103, 210, 0.1);
            }

            &::placeholder {
              color: #9aa0a6;
            }
          }

          .editing-actions {
            display: flex;
            gap: 4px;

            .confirm-btn,
            .cancel-btn {
              width: 24px;
              height: 24px;
              border: none;
              border-radius: 50%;
              cursor: pointer;
              display: flex;
              align-items: center;
              justify-content: center;
              transition: all 0.2s ease;

              i {
                font-size: 12px;
              }
            }

            .confirm-btn {
              background: #e8f0fe;

              &:hover {
                background: #d2e3fc;
              }

              i {
                color: #1967d2;
              }
            }

            .cancel-btn {
              background: #fce8e6;

              &:hover {
                background: #f6aea5;
              }

              i {
                color: #ea4335;
              }
            }
          }
        }
      }

      .collection-content {
        background: #fafbfc;
        border-left: 2px solid #fbbc04;
        margin-left: 24px;
      }
    }

    .draft-list,
    .article-list {
      .draft-item,
      .article-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        cursor: pointer;
        transition: all 0.2s ease;
        border-bottom: 1px solid #f1f3f4;

        &:hover {
          background: #f8f9fa;
        }

        &.active {
          background: #e8f0fe;
          border-left: 3px solid #1967d2;
        }

        .draft-info,
        .article-info {
          flex: 1;
          min-width: 0;

          .draft-title,
          .article-title {
            font-size: 13px;
            font-weight: 500;
            color: #202124;
            margin: 0 0 4px 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .draft-meta,
          .article-meta {
            font-size: 11px;
            color: #5f6368;
            margin: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .draft-actions,
        .article-actions {
          .action-btn {
            width: 24px;
            height: 24px;
            border: none;
            background: transparent;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: all 0.2s ease;

            &:hover {
              background: #f1f3f4;
            }

            i {
              color: #ea4335;
              font-size: 12px;
            }
          }
        }

        &:hover .draft-actions .action-btn,
        &:hover .article-actions .action-btn {
          opacity: 1;
        }
      }
    }

    .loading-spinner {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px;
      color: #5f6368;

      i {
        font-size: 16px;
      }
    }

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      color: #9aa0a6;
      font-size: 12px;

      i {
        font-size: 24px;
        margin-bottom: 8px;
        opacity: 0.5;
      }

      span {
        text-align: center;
        margin-bottom: 12px;
      }

      .create-first-collection-btn {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 12px;
        background: #e8f0fe;
        border: 1px solid #d2e3fc;
        border-radius: 16px;
        color: #1967d2;
        font-size: 11px;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          background: #d2e3fc;
          transform: translateY(-1px);
          box-shadow: 0 2px 4px rgba(25, 103, 210, 0.1);
        }

        i {
          font-size: 10px;
          opacity: 1;
        }
      }
    }
  }
}

// 动画
.collapse-enter-active,
.collapse-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.collapse-enter-from,
.collapse-leave-to {
  max-height: 0;
  opacity: 0;
}

.collapse-enter-to,
.collapse-leave-from {
  max-height: 500px;
  opacity: 1;
}

// 滚动条样式
.blog-sidebar .sidebar-content::-webkit-scrollbar {
  width: 4px;
}

.blog-sidebar .sidebar-content::-webkit-scrollbar-track {
  background: transparent;
}

.blog-sidebar .sidebar-content::-webkit-scrollbar-thumb {
  background: #c1c7cd;
  border-radius: 2px;
}

.blog-sidebar .sidebar-content::-webkit-scrollbar-thumb:hover {
  background: #9aa0a6;
}

// 动画关键帧
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
